<script>
  import $ from '../dfish.js'
  import {
    h,
    mergeProps
  } from 'vue'
  import WidgetBase from './WidgetBase.vue'
  import PubParent from './PubParent.vue'
  import Scroll from './Scroll.vue'
  import ResizeObserver from 'resize-observer-polyfill'

  export default {
    name: 'w-thead',
    mixins: [WidgetBase, PubParent],
    inject: ['table'],
    props: ['br', 'sort'],
    provide() {
      return {
        provideLeafLevel: -1,
        provideParentLeaf: null,
        provideInBody: false,
        thead: this,
      }
    },
    data() {
      return {
        rows: null
      }
    },
    methods: {
      isExpanded() {
        return true
      },
      observeTableWidth() {
        if (!this.$refs.table) return
        this.table.fixedWidth = this.$refs.table.offsetWidth + 'px'
      },
      html_tbody() {
        let cg = this.table.colgroup
        let rows = this.slots_children().map((vr, vi) => {
          $.lodash.set(vr, 'props.rowIndex', vi)
          return vr
        })
        let style = {}
        if (!this.table.fixed) {
          let mw = 0
          cg.forEach(c => {
            mw += $.number(c['min-width'] || ($.isNumber(c.width) ? c.width : 0))
          })
          if (mw) {
            style.minWidth = $.unitSize(mw)
          }
        }
        this.rows = {}
        return h('div', {
          class: 'w-table-tbl-wrap'
        }, h('table', {
          ref: 'table',
          cellpadding: 0,
          cellspacing: 0,
          class: 'w-table-tbl',
          style,
        }, [h('thead', null, h('tr', null, cg.map(v => h('td', {
            style: {
              width: v.width == '*' ? null : $.unitSize(v.width),
              minWidth: $.unitSize(v['min-width']),
            },
            'w-fixed': v.fixed
          })))),
          h('tbody', rows)
        ]))
      },
      html_slots() {
        return this.html_tbody()
      }
    },
    computed: {
      isEscape() {
        return this.x.escape
      },
    },
    mounted() {
      if (this.table.leftTable || this.table.rightTable) {
        this.$refs.table && new ResizeObserver(this.observeTableWidth).observe(this.$refs.table)
      }
    }
  }
</script>
